package rabid;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/**
 * This class represents an input file.
 * 
 * @author Andrew Bernard
 */
public class IndexedFile {
  private String fileName;
  private TermList termList;
  private List similarFiles;
  
  private class SimilarFile implements Comparable {
    public String fileName;
    public Integer similarityRating;
    
    public SimilarFile(String fileName, Integer similarityRating) {
      this.fileName = fileName;
      this.similarityRating = similarityRating;
    }
    
    public int compareTo(Object obj) {
      if(obj instanceof SimilarFile) {
        return compareTo((SimilarFile)obj);
      }
      else
        throw new ClassCastException("Cannot compare "+obj.getClass().getName() + " to a SimilarFile");
    }
    
    public int compareTo(SimilarFile file) {
      return this.similarityRating.compareTo(file.similarityRating);
    }
    
    public String toString() {
      return fileName;
    }
  }
  
  /**
   * Constructor
   */
  public IndexedFile(String fileName, String termString) {
    this.fileName = fileName;
    termList = new TermList(termString, fileName);    
  }
  
  public TermList getTermList() {
    return termList;
  }
  
  public boolean isTermInFile(String term) {
    return termList.containsKey(term);
  }
  
  public String getFileName() {
    return fileName;
  }
  
  public void setSimilarFiles(List indexedFiles) {  
    similarFiles = new ArrayList();
    Iterator files = indexedFiles.iterator();
    while(files.hasNext()) {
      IndexedFile indexedFile = (IndexedFile)files.next();
      if(!this.equals(indexedFile)) {
        int similarity = computeSimilarity(indexedFile);
        similarFiles.add(new SimilarFile(indexedFile.getFileName(), new Integer(similarity)));
      }
    }
    Collections.sort(similarFiles);
  }
  
  private int computeSimilarity(IndexedFile file) {
    int similarity = 0;
    Iterator words = termList.keySet().iterator();
    while(words.hasNext()) {
      String word = words.next().toString();
      if(file.isTermInFile(word))
        similarity++;
    }
    return similarity;
  }
  
  public Vector getSimilarFiles(int numSimilarFilesToGet) {
    Vector similarFileList = new Vector();
    int startIndex = 0;
    if(numSimilarFilesToGet < similarFiles.size())
      startIndex = similarFiles.size() - numSimilarFilesToGet;
    
    for(int i = startIndex; i < similarFiles.size(); i++) {
      similarFileList.add(similarFiles.get(i).toString());
    }
    return similarFileList;
  }
  
  public boolean equals(Object obj) {
    boolean equals = false;
    if(obj instanceof IndexedFile) {
      IndexedFile file = (IndexedFile)obj;
      equals = fileName.equals(file.getFileName());
    }
    return equals;
  }

}
